package com.example.administrator.yuejian23;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.example.administrator.yuejian23.Activity.BaseActivity;
import com.example.administrator.yuejian23.Activity.LoginActivity;

public class MainActivity extends BaseActivity {


    private LoginFragment loginFragment;
    private MainFragment mainFragment;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private LoginActivity loginActivity;

    //存储用户id

    private SharedPreferences sharedPreferences;
    private final  String fileName = "club";
    private final int MODE = MODE_PRIVATE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        sharedPreferences = getSharedPreferences(fileName,MODE);

        if(isLogined()){
            showMainFragment();
            userId = readUserId();


        }else {
           showLoginFragment();
        }


    }
    private void showLoginFragment(){
        fragmentTransaction = fragmentManager.beginTransaction();
        loginFragment = new LoginFragment();
        fragmentTransaction.add(R.id.fragment_holder,loginFragment);
        fragmentTransaction.commit();

    }
    private void showMainFragment(){
        fragmentTransaction = fragmentManager.beginTransaction();
        mainFragment = new MainFragment();
        fragmentTransaction.add(R.id.fragment_holder,mainFragment);
        fragmentTransaction.commit();

    }
    public void replaceLoginFragment(){
        fragmentTransaction = fragmentManager.beginTransaction();
        mainFragment = new MainFragment();
        fragmentTransaction.replace(R.id.fragment_holder,mainFragment);
        fragmentTransaction.commit();


    }
    private boolean isLogined(){
        //String userId = readUserId();
        userId = readUserId();
        return !userId.equals("-1");
    }

    private  String readUserId(){
        String userId = sharedPreferences.getString("userID","-1");

        return userId;
    }
    public void saveUserId(String userId){
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("userID",userId);
        editor.commit();


    }
}
